package com.roc.live.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.Nullable;

import com.roc.live.LiveApplication;
import com.roc.live.model.NetworkType;
import com.roc.live.util.LiveUtil;
import com.roc.live.util.StringUtil;
import com.upyun.hardware.AsyncRun;
import com.upyun.hardware.AudioEncoder;
import com.upyun.hardware.Config;
import com.upyun.hardware.PushClient;

import java.text.DecimalFormat;


/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 */
public class LiveIntentService extends IntentService {
    public static final String ServiceName = LiveIntentService.class.getSimpleName();
    private static final String Tag = LiveIntentService.class.getSimpleName();

    private PushClient mClient;
    private Config config;
    private String rtmpUrl = "rtmp://47.95.194.168:8801/live/roc";

    public LiveIntentService() {
        super(ServiceName);
    }

    public static void startMyself(Context context, String action) {
        Intent intent = new Intent(context, LiveIntentService.class);
        intent.setAction(action);
        context.startService(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        config = new Config.Builder().URL(rtmpUrl).build();
        mClient = new PushClient(LiveApplication.getAppContext(), config);
        mClient.setReconnectEnable(true);//开启自动重连
        mClient.setAdjustBitEnable(true);
        mClient.setOnRtmpPublishListener(mRtmpPublishListener);
        AudioEncoder.NOISE = true;
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Log.d(Tag, "onStartCommand");
        NetworkType type = LiveUtil.getNetworkType();
        Log.d(Tag, "the network type is:" + type);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (StringUtil.isEmpty(action)) {
                return;
            }

            NetworkType type = LiveUtil.getNetworkType();
            if (type != NetworkType.WIFI) {
                return;
            }

            switch (action) {
                case LiveServiceCmd.LIVE:
                    Log.d(Tag, "LiveIntentService onHandleIntent....");
                    break;
            }

            if (mClient.isStart()) {

            } else {
                try {
                    mClient.startPush();
                } catch (Exception e) {
                    Log.d(Tag, e.getMessage(), e);
                }
            }
//            while (true) {
//                Log.d(Tag, "onHandleIntent ...............");
//                try {
//                    Thread.sleep(5000);
//                } catch (Exception e) {
//
//                }
//            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(Tag, "LiveIntentService onDestroy....");
    }

    private PushClient.RtmpPublishListener mRtmpPublishListener = new PushClient.RtmpPublishListener() {
        @Override
        public void onRtmpPublishInfo(final int bitrate, final double fps, final long totalSize) {
            AsyncRun.run(new Runnable() {
                @Override
                public void run() {
                    DecimalFormat df = new DecimalFormat("######0.0");
                    StringBuilder sb = new StringBuilder();
                    sb.append("bitrate:  " + bitrate + "kbps\r\n");
                    sb.append("fps:  " + df.format(fps) + "fps\r\n");
                    sb.append("totalsize:  " + totalSize + "KB\r\n");
//            Log.e(TAG, "bitrate:" + bitrate + "kbps, fps:" + df.format(fps) + "fps, totalSize:" + totalSize + "KB");
                    Log.d(Tag, sb.toString());
                }
            });
        }
    };
}
